<template>
  <div class="mainList">
    <div class="searchMain">
      <div class="searchPos" :class="{'boxShow': searchHide}">
        <a-form ref="formSearchRef" :model="formSearch" v-if="columnsDistShow">
          <div class="form-main" :class="{'searchHide': searchHide}">
            <div class="form-item">
              <!-- <div class="searchTop-list tess">
                <a-select v-model="formSearch.keywords_type"
                      style="width:165px;"
                      :trigger-props='{trigger:"hover"}'
                      :bordered="false"
                      :options="keywordTypes"
                      default-value="keywords"
                      @change="(v)=>switchKeywordType(formSearch,v)">
                </a-select>
                <a-input v-model="formSearch[formSearch['keywords_type']??'keywords']" allow-clear placeholder="多个请用','割开"/>
              </div>
              <a-form-item :field="formSearch['keywords_type']" label="关键字" label-col-flex="90px" style="display: none;"></a-form-item> -->
              <a-form-item field="shipment_no" label="箱唛" label-col-flex="90px" class="searchTop-list">
                <a-input v-model="formSearch.shipment_no" allow-clear placeholder="清输入箱唛"/>
                </a-form-item>
                <a-form-item field="address_id" :disabled="tableTabs" label="目的地" label-col-flex="90px" class="searchTop-list">
                  <a-select v-model="formSearch.address_id" :max-tag-count="1" :options="columnsDist.dicthelpApi_addressChang.data" :field-names="{ value: 'value', label: 'label' }"
                  placeholder="请选择目的地" allow-clear allow-search :virtual-list-props="{height:200}">
                    </a-select>
                </a-form-item>
                <a-form-item field="car_number" label="车牌号" label-col-flex="90px" class="searchTop-list">
                <a-input v-model="formSearch.car_number" allow-clear placeholder="清输入车牌号"/>
                </a-form-item>
                <a-form-item field="container_no" label="柜号" label-col-flex="90px" class="searchTop-list">
                <a-input v-model="formSearch.container_no" allow-clear placeholder="清输入柜号"/>
                </a-form-item>
                <a-form-item field="intercept" label="是否拦截" label-col-flex="90px" class="searchTop-list">
                  <a-select v-model="formSearch.intercept"
                          placeholder="请选择是否拦截" allow-clear allow-search>
                  <a-option value="1">已拦截</a-option>
                  <a-option value="2">未拦截</a-option>
                </a-select>
                </a-form-item>
              <a-form-item field="depot_id" :disabled="tableTabs" label="仓库" label-col-flex="90px" class="searchTop-list">
                  <a-select  v-model="formSearch.depot_id" :max-tag-count="1" :options="columnsDist.dicthelpApi_depot.data" :field-names="{ value: 'id', label: 'name' }"
                  placeholder="请选择仓库" allow-clear allow-search :virtual-list-props="{height:200}">
                    </a-select>
                </a-form-item>
                <a-form-item field="service_type_id" label="服务类型" label-col-flex="90px" class="searchTop-list">
                  <a-select  v-model="formSearch.service_type_id" :max-tag-count="1" :options="columnsDist.dicthelpApi_waybillServiceShipmentTypeList.data" :field-names="{ value: 'id', label: 'name' }"
                  placeholder="请选择服务" allow-clear allow-search :virtual-list-props="{height:200}">
                    </a-select>
                </a-form-item>  
                <a-form-item field="send_no" label="出库单标题" label-col-flex="90px" class="searchTop-list">
                  <a-input v-model="formSearch.send_no" allow-clear placeholder="请输入出库单标题"/>
                </a-form-item>
            </div>     
            <div class="form-buttom">
              <div>
                <a-button type="primary" html-type="submit" @click="submitSearch" style="margin-right: 10px;">
                  <template #icon>
                    <icon-search/>
                  </template>
                  搜索
                </a-button>
                <a-button @click="resetSearch">
                  <template #icon>
                    <icon-delete/>
                  </template>
                  重置
                </a-button>
              </div>      
              <a-space class="lg:mt-0 mt-2" style="margin-top: 20px;display: flex;justify-content: flex-end;margin-right: 10px">         
                  <a-tooltip content="显隐搜索"><a-button shape="circle" @click="searchHide=!searchHide"  style="margin-right: 10px"><icon-search/></a-button></a-tooltip>
                  <a-tooltip content="设置"><a-button shape="circle" @click="openSetting"><icon-settings/></a-button></a-tooltip>
                </a-space>                  
            </div>
          </div>
        
          <div class="touHide" style="display: flex;justify-content: center;margin-bottom: 10px;">  
            <a-link v-if="searchHide" @click="searchHide=!searchHide" size="small">
              {{ searchHide ? '收起':'' }}
              <template #icon>
                <icon-up v-if="searchHide" />
              </template>
            </a-link>
          </div>
          </a-form>
      </div>
    </div>
    <div class="ma-content-block justify-between p-4 mainTable">
          <!-- 操作按钮 -->
          <div class="top-button">
            <div>
                <!-- <a-button type="primary" @click="addAction()">
              <template #icon>
                <icon-plus/>
              </template>
              新增
            </a-button> -->
            </div>
        <a-space class="lg:mt-0 mt-2">         
          <a-tooltip content="显隐搜索"><a-button shape="circle" @click="searchHide=!searchHide" ><icon-search/></a-button></a-tooltip>
          <a-tooltip content="设置"><a-button shape="circle" @click="openSetting"><icon-settings/></a-button></a-tooltip>
        </a-space>
            
        </div>
        <!-- tab切换 -->
        <a-tabs class="ma-tabs mb-1 tabs" @change="clickTap" v-if="!tableTabs" v-model:active-key="formSearch.status">         
          <a-tab-pane :key="item.key" :title="item.title" v-for="item in shipmentTabs">
            <template #title>
              <slot :name="'tabTitle-' + item.label">{{ item.title }}{{ item.count ? `(${item.count})` : '' }}</slot>
            </template>
          </a-tab-pane>
      </a-tabs>
      <div style="display: flex;">
        <button-group :button-groups="buttonGroups" :dataList="dataList" :crud-ref="crudRef" :selected="selected"
                      :currentStatus="currentStatus"/>
      </div>
      <div ref="tablePrantRef">
      <a-table ref="tableRef" :sticky-header="true" :scrollbar="true" :stripe="true" :scroll="{ x: '100%', y: '100%' }"  :columns="localColumns(columnsData,formSearch.status,'waybillList')" :data="dataList" class="table-list" 
    hide-expand-button-on-empty :loading="loading" row-key="id" v-model:selectedKeys="selected" @selection-change="setSelecteds($event)" stripe :row-selection="rowSelection" column-resizable :pagination="false">
      <!--  列表插槽    -->
        <!-- <template #status="{ record }" v-if="columnsDistShow">{{getDictData('dictObj','waybill_sea_list_status',record.status,2,columnsDist) }}</template>  -->
        <template #depot_id="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_depot',record.shipment.order.depot_id,3,columnsDist) }}</template>
        <template #service_type_id="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_waybillServiceShipmentTypeList',record.shipment.service_type_id,3,columnsDist) }}</template>
        
        <template #shipment_no="{ record }">
          {{record.shipment.shipment_no  }}
          <a-link status="danger" v-if="record.shipment.is_intercept == 1">
              <template #icon>
                <icon-stop/>
              </template>
              拦截
            </a-link>
        </template>
        <template #car_number="{ record }">
          {{record?.send?.car?.car_number  }}
        </template>
        <template #address_desc="{ record }">{{record.tray?.address_desc}}</template>
        <template #send="{ record }">
          <a-tooltip :content="'预计送达时间：'+record.send?.eta">
              <span>{{record.send?.title}}</span>
            </a-tooltip>
        </template>
        <template #tracking_no="{ record }">
          {{record.send?.tracking_no}}
        </template>
      <template #isa="{ record }">
           <div style="display: flex;align-items: center;">
              <div style="margin-right: 8px;"> {{record?.send?.car?.isa?.remark}}</div>
              <a-link title="下载ISA"  @click="downloadatAachable(record.send.car.isa)" v-if="record?.send?.car?.isa?.filepath">
                  <icon-to-bottom/>
              </a-link>
           </div>
        </template>
        <template #pod="{ record }">
            <a-link title="下载POD"  @click="downloadatAachable(record.send.car.pod)" v-if="record?.send?.car?.pod?.filepath">
              <icon-to-bottom/>下载
          </a-link>
        </template>
      <template #fixed="{ record }">
          <a-link :disabled="record.status==1" title="详情" @click="editAction(record)"><icon-book /></a-link>
          </template>
      </a-table>
    </div>  
    <!-- 分页 -->
    <div class="foot-list">
      <a-pagination
          :total="pageInfo.total"
          show-total show-jumper show-page-size     
          v-model:current="formSearch.page"
          @change="pageChange"
          @page-size-change="pageSizeChange"
          :page-size-options="[10, 20, 30, 50, 100]"
          :page-size="formSearch.pageSize"
          style="display: inline-flex"
      />
    </div>
    <add-modal-form ref="addModalMormRef" @addClick="tableList" v-if="columnsDistShow"></add-modal-form>
    <add-modal-send-form ref="addModalMormSendRef" @addClick="tableList" v-if="columnsDistShow"></add-modal-send-form>
    <setting ref="settingRef"></setting>
  </div>
</div>

</template>
<script setup lang="jsx">
import {ref, reactive, provide, computed, watch,onMounted,h,getCurrentInstance} from 'vue'
import {onBeforeRouteLeave} from "vue-router";
import waybillTrayList from '@/api/abroad/waybillTrayList'
import waybillTaskSend from '@/api/abroad/waybillTaskSend'
import AddModalForm from "@/views/abroad/waybillList/components/addModalForm.vue";
import AddModalSendForm from "@/views/abroad/waybillTaskSend/components/addModalForm.vue";
import {getDictData} from "@/utils/crud/dictNew.js";
import common from "@/api/common.js";
import dicthelpApi from "@/api/dicthelpApi.js";
import ButtonGroup from "@cps/actionsNew/buttonGroup.vue";
import Setting from "@/views/components/setting.vue";
import {localColumns,tablePrantRefHeight} from "@/utils/crud/culmns.js";
import uploadConfig from '@/config/upload'
import tool from '@/utils/tool'
import { useAppStore, useUserStore } from '@/store'
const crudRef = ref()
const addModalMormRef = ref()
const addModalMormSendRef=ref()
const selected=ref([])
const columnsDistShow=ref(false)
const shipmentTabs=ref([])//tabs赋值
const countList=ref({})
const tableRef = ref()
const tablePrantRef = ref() //tabel 父级高度
const dataList = ref([])
const loading=ref(false)
const settingRef = ref()
const columnsDist = ref([])
const formSearchRef=ref(null)
const userStore = useUserStore()
//搜索更多是否显示
const searchHide=ref(false)
const currentStatus = computed(() => {
  let requestParams = formSearch
  if (!requestParams.status) {
    return null;
  }
  return requestParams.status
})
watch([shipmentTabs,countList],
(newValues) => {
  if(shipmentTabs.value!='' && countList.value!=''){
      shipmentTabs.value.forEach(function(item) {
            item.count = countList.value[item.key] ? countList.value[item.key] : 0
      })   
  }
  }
)
const columnsData = ref([  
{title: '仓代码', dataIndex: 'depot_id',slotName: 'depot_id',width:70,align:'center',hide:true,},
{title: '柜号', dataIndex: 'shipment.container_no',width:100,align:'center',hide:true,},
{title: '服务类型', dataIndex: 'service_type_id',slotName: 'service_type_id',width:150,align:'center',hide:true,},
{title: '目的地', dataIndex: 'address_desc',slotName: 'address_desc',width:100,align:'center',hide:true,},
{title: '箱唛', dataIndex: 'shipment_no',slotName: 'shipment_no',width:100,align:'center',hide:true,},
// {title: '可用库存', dataIndex: 'count',width:100,align:'center',hide:false,},
{title: '入库日期', dataIndex: 'shipment.unpacking_at',width:150,align:'center',hide:true,},
{title: '托盘组', dataIndex: 'tray.number',width:100,align:'center',hide:true,},
{title: '托盘（总）', dataIndex: 'shipment.tray_count_actual',width:100,align:'center',hide:true,},
{title: '入库重量', dataIndex: 'shipment.weight',width:100,align:'center',hide:true,},
{title: '库存CBM', dataIndex: 'shipment.volume',width:100,align:'center',hide:true,},
{title: '库龄/天', dataIndex: 'shipment.age',width:100,align:'center',hide:true,},
{title: '车牌号', dataIndex: 'car_number',slotName: 'car_number',width:70,align:'center',hide:true,},
{title: 'POD', dataIndex: 'pod',slotName: 'pod',width:70,align:'center',hide:true,},
{title: 'ISA', dataIndex: 'isa',slotName: 'isa',width:70,align:'center',hide:true,},
{title: '仓租', dataIndex: 'shipment.day_fee',width:100,align:'center',hide:false,},
{title: '出库单信息', dataIndex: 'send',slotName: 'send',width:150,align:'center',hide:false,},
{title: '追踪编号', dataIndex: 'tracking_no',slotName: 'tracking_no',width:150,align:'center',hide:false,},
{title: '在库箱数', dataIndex: 'count',width:100,align:'center',hide:false,},
{title: '操作', slotName: 'fixed',fixed: 'right',width: 107,align:'center',hide:true,},
]);

const statistics = ref({
  count: 0,
  weight:0,
})
onBeforeRouteLeave(() => {
  statistics.notify && statistics.notify.close()
})
const notification = getCurrentInstance().appContext.config.globalProperties.$notification;
watch(() => selected,
    (v) => {
      if(!tableTabs.value){
        return;
      }
      if (!v.value || v.value.length === 0) {
        statistics.notify && statistics.notify.close()
        return;
      }
      const records = dataList.value.filter(i => selected.value.indexOf(i.id) > -1)

      statistics.value = {
        count: records.reduce((acc, cur) => acc + Number(cur.count), 0),
        weight: records.reduce((acc, cur) => acc + Number(cur.shipment.weight), 0),

      }
      statistics.notify = notification.warning({
        id: 'addToWaybillStatistics',
        content: <div class="grid grid-cols-2 gap-2">
          <span>在库箱数合计:{statistics.value.count}</span>
          <span>入库重量合计:{statistics.value.weight}</span>
        </div>,
        position: "bottomLeft",
        duration: 0,
        class: ['bg-red-400 p-1'],
        style: {
          width: '20vw',
          left:'100%'
        },
        showIcon: false
      })
    },
    {deep: true,}
)
//下载
const downloadatAachable=(item)=>{
  let url=uploadConfig.storage.OSS+item.filepath
  window.location.href=url
}

const openSetting=()=>{
  settingRef.value.open()
}
//新增
const addAction=()=>{
  addModalMormRef.value.onShow()
}
//详情
const editAction=(record)=>{
  addModalMormRef.value.onShow(record)
}
const tableTabs=ref(false)
const tableAddress_id=ref('')
const open = async (address_id,type_status) => {
  tableTabs.value=true
  formSearchRef.value.resetFields();
  formSearch.page=1
  formSearch.status=type_status
  tableAddress_id.value=address_id
  tableList()
}
//总页数
const pageInfo = ref({
  currentPage: 1,
  total: 0,
  totalPage:1
})
//table 选择
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  checkStrictly: true
});
//列表请求数据
const formSearch=reactive({
  depot_id: '',
  service_type_id: '',
  car_number:'',
  address_id:'',          
  shipment_no:'',
  send_no:'',
  container_no:'',
  created_at: [], 
  scence:'shipment-all',
  intercept:null,
  refresh_tabs: 1,
  page: 1,
  pageSize: 10,
  status: '1',
  })
    //重置
  const resetSearch=(e)=>{
    formSearchRef.value.resetFields();
    console.log('formSearch',formSearch)
    tableList()
  }
 //搜索 
 const submitSearch=(e)=>{
  formSearch.page=1
  formSearch.refresh_tabs=1
  searchHide.value=false
  tableList()
}
  //切换分页
const pageChange=(e)=>{
  if(e){
   formSearch.page=e
    tableList()
  }
}
  //切换条数
const pageSizeChange=(e)=>{
  if(e){
  tool.local.set('pageSize', e)
   formSearch.pageSize=e
    tableList()
  }
}
//行数选中
const setSelecteds = (key) => {
  selected.value = key
}
//tabs切换
const clickTap=(e)=>{
  formSearch.page=1
  formSearch.status=e
  formSearch.refresh_tabs=0
    tableList()
}
    //列表
    const tableList = () => {
      loading.value=true
      if(tableTabs.value){
        formSearch.refresh_tabs=0
        formSearch.address_id=tableAddress_id.value
        formSearch.is_intercept=0
        formSearch.depot_id=userStore.currentDepot.id
      }
      formSearch.pageSize=tool.local.get('pageSize') || 10
      waybillTrayList.getList(formSearch).then(res => {    
        dataList.value =  res.data.items
        //页数
        pageInfo.value = res.data.pageInfo
        countList.value=res.data.count   
        formSearch.status=res.data.current_type.toString()
        selected.value=[]
        loading.value=false
        tablePrantRefHeight(tablePrantRef.value)
      })      
    }
  
    onMounted(() => {
      tableList()
    })

const keywordTypes = [
  //  转单号   供应商单号
  {value: 'keywords', label: '单号'},
  // {value: 'public_number', label: '系统提单号'},
  {value: 'shipment_no', label: '运单号'},
  {value: 'outer_carrier_tracking_number', label: '转单号',index:'快递单号'},
  {value: 'ext_number', label: '扩展单号'},
  // {value: 'number', label: '客户单号'},
]
const switchKeywordType = (form,value)=>{
  keywordTypes.map(i=>{
    if(form[i.value] && i.value !== value){
      form[value] = form[i.value]
      form[i.value] = undefined
    }
  })
}
//字典
const waybillColumns= async () => {
  let attrDict=['waybill_sea_tray_status']
  let [dictObj,dicthelpApi_depot,dicthelpApi_waybillServiceShipmentTypeList,dicthelpApi_addressChang,dicthelpApi_waybillCarList]=await Promise.all([
    common.getDicts(attrDict),dicthelpApi.depot({sea:1}),
        dicthelpApi.waybillServiceShipmentTypeList(),dicthelpApi.addressChang(0),dicthelpApi.waybillCarList()
    ])
  return reactive({
        dictObj,
        dicthelpApi_depot,
        dicthelpApi_waybillServiceShipmentTypeList,
        dicthelpApi_addressChang,
        dicthelpApi_waybillCarList,
    })
}

waybillColumns().then(res=>{
  console.log('jjjjjjjjjjjj',res)
  columnsDist.value=res
  columnsDistShow.value=true
  let parcelType=res.dictObj.data.waybill_sea_tray_status
  if(parcelType){
    let obj={
      id:'',
      title:'全部',
      key:'',
    }    
    parcelType.push(obj)
    shipmentTabs.value=parcelType
  }
})
const buttonGroups = [
{
    title: '分配出库单',
    api:waybillTrayList.taskTap,
    auth: ['sea:waybillTrayList:task'],
    hideStatus: [2, 3, 4, 5, null],
    send:true,
    form: {
          //  key: 'id',
          // id:'number',
          form: {
            type:2,
          },
          columns: [
            {
              title: '出库单', dataIndex: 'send_id', formType: 'select',
              rules: {required: true, message: "请选择出库单"},
              dict: {
                url: 'sea/waybillTaskSend/list',
                props: {label: 'title', value: 'id'},
                translation: true,
              },
              addApi: () => {
                addModalMormSendRef.value.onShow()
                },
            }
          ]
        }
  },{
    title: '移除出库单',
    api:waybillTrayList.deleteTask,
    auth: ['sea:waybillTrayList:deleteTask'],
    hideStatus: [1,3, 4, 5, null],
    form: {
          // key: 'list',
          // id:'number',
      //  form: {
      //       type:2,
      //     },
        }
  },{
    title: '上车',
    api:waybillTrayList.carin,
    auth: ['sea:waybillTrayList:carin'],
    hideStatus: [1,3, 4, 5, null],
  },{
    title: '下车',
    api:waybillTrayList.carout,
    auth: ['sea:waybillTrayList:carout'],
    hideStatus: [1,2, 4, 5, null],
    carType:true,
    form: {
      form: {
          count: 1,
        },
      columns: [
          {
              title: '数量', dataIndex: 'count', formType: 'input-number',min:1,
              rules: {required: true, message: "请输入数量"},
            }
          ]
        }
  },{
    title: '完成',
    api: waybillTrayList.closeTap,
    auth: ['sea:waybillTrayList:close'],
    hideStatus: [2, 3, 4, 5, null],
    form: {
          key: 'ids',
          id:'id',
        }
  },{
    title: '取消拦截',
    api: waybillTrayList.uintercept,
    auth: ['sea:waybillTrayList:unintercept'],
    hideStatus: [null],
    listSelected:'id',
    form: {
          key: 'ids',
          id:'shipment_id',
        }
  },{
    title: '拦截',
    api: waybillTrayList.intercept,
    auth: ['sea:waybillTrayList:intercept'],
    hideStatus: [null],
    listSelected:'id',
    form: {
          key: 'ids',
          id:'shipment_id',
        }
  },
  // {
  //   title: '绑定托盘',
  //   api:waybillTrayList.trayShipment,
  //   auth: ['sea:waybillTrayList:trayShipment'],
  //   hideStatus: [2, 3, 4, 5, null],
  //   form: {
  //         key: 'ids',
  //         id:'id',
  //         form: {
  //           count: 1,
  //         },
  //         columns: [
  //           {
  //             title: '托盘号', dataIndex: 'number', formType: 'input',
  //             rules: {required: true, message: "请输入托盘号"},
  //           },{
  //             title: '数量', dataIndex: 'count', formType: 'input-number',min:1,
  //             rules: {required: true, message: "请输入数量"},
  //           }
  //         ]
  //       }
  // },
]
provide('tableList',tableList);
provide('getDictData',getDictData)
provide('columnsData', columnsData)
provide('columnsDist', columnsDist)//全部字典
provide('dataList', dataList)
provide('formSearch', formSearch)
provide('selected', selected)
defineExpose({ open,selected })

</script>
<script lang="jsx"> export default {name: 'sea:waybillList'} </script>
<style scoped>
.form-inline-card > .arco-card-body {
  padding: 0;
  display: grid;
  grid: 1fr / 1fr 1fr 1fr;
}

.form-inline-card > .arco-card-header {
  display: none;
}

.fee-up {
  border-bottom: dashed #777777 1px;
}

.fee-down {
  color: orange;
}
.customer-input-item .arco-btn-group button:first-child{
  display:none;
}

.table-list{
  margin-top:5px;
}
.arco-tabs-content{
  padding:0;
}
.foot-list{
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.mainTable{
  padding-top: 68px;
}
.arco-select-view-inner{
  white-space: nowrap;
}
.arco-select-view-inner .arco-tag{
  white-space: nowrap !important;
}
.tabs .arco-tabs-tab{
  min-width: 70px;
  justify-content: center;
}
</style>